﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net;
using DotNetOpenAuth.OAuth2;

namespace MasoQna.Infrastructure.Auth
{
    public class FacebookHandler : IAuthHandler
    {
        public FacebookHandler()
        {
            imagePath = "/Content/image/facebook.png";
        }

        public void StartAuthentication()
        {
            IAuthorizationState authorization = client.ProcessUserAuthorization();
            if (authorization == null)
            {
                // Kick off authorization request
                client.RequestUserAuthorization();
            }
        }

        public bool FinishAuthenticaiton(out string providedUserId)
        {
            IAuthorizationState authorization = client.ProcessUserAuthorization();

            var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
            using (var response = request.GetResponse())
            {
                using (var responseStream = response.GetResponseStream())
                {
                    var graph = FacebookGraph.Deserialize(responseStream);
                    providedUserId = graph.Id.ToString();
                    //HttpContext.Current.Session["userId"] = providedUserId;
                }
            }

            return true;
        }

        public string ImagePath
        {
            get { return imagePath; }
        }

        static FacebookHandler()
        {
            client = new FacebookClient
            {
                ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
                ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["facebookAppSecret"]),
            };
        }

        private static FacebookClient client;
        private string imagePath;
    }
}